#coding=utf8
#LightCam 处理snmpinterface.txt程序
#init by hfh 20150608

import time,re,sys,traceback,threading,os,json
import lc_libs

if __name__ == "__main__":


	lchome=lc_libs.lc_getlchome()
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	
	today=time.strftime('%Y%m%d',time.localtime())
	os.system("mv %s %s.%s" % (logfilename,logfilename,today))
	
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()

	try:
		#初始化数据库
		db=lc_libs.lc_mongodb_operater('127.0.0.1',27017)

		db.connect()
		Conn=db.getConn()
		if Conn==None:
			print "Can not Connect to the MondbDB"
			exit(0)
		
		perf_dbname='lc_perf'
		snmpinterface_tablename='lc_snmpinterface'
		
		perf_db=db.useDatabase(perf_dbname)
		snmpinterface_table=db.UseCollection(perf_db,snmpinterface_tablename)

	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" 初始化数据库失败:\n"+excinfo+"\n")
		logfile.flush()
		exit(0)

	while True:
		time.sleep(0.1)
		
		try:
			cmd='scp ywn_monitor1:/monitor/bin/network/snmp_interface.txt /tmp/'
			#cmd='scp ywn_monitor1:/monitor/imonitor/bin/network/snmp_interface.txt /tmp/'
			#cmd='id'
			os.system(cmd)
			
			#logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			#logfile.write("%s 当前时间标识 : %s 延时：%s秒。\n" % (logdate,timeflag,int(time.time())-timeflag))
			#logfile.flush()
			
			ifile=open('/tmp/snmp_interface.txt','r')
			idata=ifile.readlines()
			ifile.close()
			
			idict=[]
			iport={}
			key=''
			value=''
			
			for lines in idata:
				
				if 'Device=' in lines and len(iport)<>0:
					idict.append(iport)
					new=int(time.time())
					iport={}
					key=lines.split('=')[0].strip('\r\n\t')
					value=lines.split('=')[1].strip('\r\n\t')
					iport[key]=value
					
				if len(iport)==0:
					new=int(time.time())
					iport={'LCTime':new}
						
				key=lines.split('=')[0].strip('\r\n\t')
				value=lines.split('=')[1].strip('\r\n\t')
				iport[key]=value
				
			idict.append(iport)
			
			#暂时不入库
			#for iport in idict:
			#	db.insertDatas(snmpinterface_table,iport)
			
			#暂时不生成全量json
			#jfile=open(lchome+'/pyweb/static/json/network/snmpinterface.json','w')
			#jfile.write(json.dumps(idict))
			#jfile.close()
			
			#读取设备与IP对应关系表
			devicelist={}
			dfile=open('/opt/netcool/omnibus/lookuptables/cffe_device.txt','rb')
			for line in dfile.readlines():
				lines=line.split('\t')
				devicelist[lines[0]]=lines[1]
			
			#生成用于判断端口状态的专用json
			jdata={}
			for iport in idict:
				if devicelist.has_key(iport['Device']) and iport.has_key('ifDescr') and iport.has_key('StringOperStatus'):
					jkey=devicelist[iport['Device']]+"-"+iport['ifDescr']
					jdata[jkey]=iport['StringOperStatus']
				else:
					pass
			
			jfile=open(lchome+'/pyweb/static/json/network/interface.json','w')
			jfile.write(json.dumps(jdata))
			jfile.close()
		
		except Exception:
			excinfo=traceback.format_exc()
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			logfile.write(logdate+" :\n"+excinfo+"\n")
			logfile.flush()
		
		time.sleep(60)
